package com.xwj.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 原子引用方式实现自旋锁
 *
 * @author xwj
 * @date 2020/3/10
 */
public class SpinLockDemo {
    private AtomicReference<Thread> threadAtomicReference = new AtomicReference<>();

    public void lock() {
        Thread current = Thread.currentThread();
        System.out.println("lock:" + current.getName());
        while (!threadAtomicReference.compareAndSet(null, current)) {

        }
    }

    public void unlock() {
        Thread current = Thread.currentThread();
        System.out.println("unlock:" + current.getName());
        threadAtomicReference.compareAndSet(current, null);
    }


    public static void main(String[] args) {
        SpinLockDemo spinLockDemo = new SpinLockDemo();
        new Thread(
                () -> {
                    spinLockDemo.lock();
                    try {
                        TimeUnit.MILLISECONDS.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    spinLockDemo.unlock();
                }, ("A")
        ).start();

        try {
            TimeUnit.MILLISECONDS.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(
                () -> {
                    spinLockDemo.lock();
                    System.out.println("获取锁了");
                    spinLockDemo.unlock();
                }, ("B")
        ).start();

    }
}
